package dataStruct;

import java.util.Arrays;
import java.util.EmptyStackException;

/**
 * @Author wangtengyu
 * @Create 2018-03-22-14:22
 * 自己实现一个栈结构
 */
public class MyStack {

    private Object[] elementData;
    private int top;
    private int size;

    //默认构造一个长度为10的栈
    public MyStack() {
        this.size = 10;
        this.top = -1;
        elementData = new Object[size];
    }

    public MyStack(int initCapacity) {
        if (initCapacity < 0) {
            throw new IllegalArgumentException("栈初始容量不能小于0");
        }
        this.size = initCapacity;
        this.top = -1;
        elementData = new Object[size];
    }

    //压栈
    public Object push(Object item) {
        isGrow(top + 1);
        elementData[++top] = item;
        return item;
    }


    //返回栈顶元素
    public Object peek() {
        if (top == -1) {
            throw new EmptyStackException();
        }
        return elementData[top];
    }

    //弹出栈顶元素
    public Object pop() {
        Object obj=peek();
        remove(top);
        return obj;
    }


    //删除栈顶元素
    public void remove(int top) {
        elementData[top]=null;
        this.top--;
    }

    //判断栈是否为空
    public boolean isEmpty() {
        return (top == -1);
    }


    //是否扩容
    public boolean isGrow(int capaCity) {
        int oldCapaCity = size;
        if (capaCity >= oldCapaCity) {
            int newCapaCity = 0;
            if ((oldCapaCity << 1) - Integer.MAX_VALUE > 0) {
                newCapaCity = Integer.MAX_VALUE;
            } else {
                newCapaCity = (oldCapaCity << 1);
            }
            this.size = newCapaCity;
            elementData = Arrays.copyOf(elementData, size);
            return true;
        } else {
            return false;
        }
    }



    public static void main(String[] args) {
        MyStack stack = new MyStack(3);
        stack.push(1);
        //System.out.println(stack.peek());
        stack.push(2);
        stack.push(3);
        stack.push("abc");
        System.out.println(stack.peek());
        stack.pop();
        stack.pop();
        stack.pop();
        System.out.println(stack.peek());
        //System.out.println(stack.size);
    }


}
